<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { uploadPictureByBatchUsingPost } from '@/api/pictureController'

const router = useRouter()

// 表单数据
const form = ref({
  searchText: '',
  count: 10,
  namePrefix: ''
})

// 进度相关状态
const isFetching = ref(false)
const fetchProgress = ref(0)
const fetchStatus = ref('')

// 提交表单
const handleSubmit = async () => {
  if (!form.value.searchText) {
    message.error('请输入搜索词')
    return
  }

  if (form.value.count <= 0 || form.value.count > 30) {
    message.error('抓取数量必须在1-30之间')
    return
  }

  try {
    isFetching.value = true
    fetchStatus.value = '正在提交抓取任务...'
    fetchProgress.value = 0

    // 更流畅的进度模拟
    let progress = 0
    const totalSteps = 100 // 总进度步数
    const targetSteps = 90 // 最大进度（不包括最后的完成步骤）
    const stepInterval = Math.max(100, 2000 / totalSteps) // 根据任务时间调整步进间隔

    const progressInterval = setInterval(() => {
      if (progress < targetSteps) {
        progress += 1;
        fetchProgress.value = progress;

        // 根据进度更新状态文本
        if (progress < 30) {
          fetchStatus.value = `正在初始化抓取任务... ${progress}%`
        } else if (progress < 60) {
          fetchStatus.value = `正在搜索"${form.value.searchText}"相关图片... ${progress}%`
        } else if (progress < 80) {
          fetchStatus.value = `已找到${form.value.count}张相关图片，准备下载... ${progress}%`
        } else {
          fetchStatus.value = `正在处理图片数据... ${progress}%`
        }
      }
    }, stepInterval)

    // 执行实际的API调用
    const res = await uploadPictureByBatchUsingPost(form.value)

    // 清除进度模拟
    clearInterval(progressInterval)

    if (res.data.code === 0) {
      // 快速完成最后的进度
      fetchProgress.value = 100
      fetchStatus.value = '抓取任务已完成，正在跳转...'

      message.success('图片批量抓取任务已提交')
      // 延迟跳转，让用户看到完成状态
      setTimeout(async () => {
        await router.push('/')
      }, 1500)
    } else {
      fetchStatus.value = '抓取任务提交失败'
      fetchProgress.value = 0
      message.error(res.data.message || '操作失败')
      isFetching.value = false
    }
  } catch (err) {
    fetchStatus.value = '抓取任务提交失败'
    fetchProgress.value = 0
    message.error('操作失败')
    isFetching.value = false
  }
}
</script>

<template>
  <div class="add-picture-batch-page">
    <a-card title="批量抓取图片">
      <a-form :model="form" layout="vertical">
        <a-form-item
          label="搜索词"
          required
          help="请输入要搜索的关键词，系统将根据关键词抓取相关图片"
        >
          <a-input
            v-model:value="form.searchText"
            placeholder="请输入搜索关键词"
            :disabled="isFetching"
          />
        </a-form-item>

        <a-form-item
          label="抓取数量"
          help="请输入要抓取的图片数量（不超过30）"
        >
          <a-input-number
            v-model:value="form.count"
            :min="1"
            :max="30"
            style="width: 100%"
            :disabled="isFetching"
          />
        </a-form-item>

        <a-form-item
          label="名称前缀"
          help="可选，为抓取的图片设置统一的名称前缀"
        >
          <a-input
            v-model:value="form.namePrefix"
            placeholder="请输入图片名称前缀（可选）"
            :disabled="isFetching"
          />
        </a-form-item>

        <!-- 进度显示区域 -->
        <div v-if="isFetching" class="progress-section">
          <div class="progress-info">{{ fetchStatus }}</div>
          <a-progress :percent="fetchProgress" status="active" />
        </div>

        <a-form-item>
          <a-button
            type="primary"
            @click="handleSubmit"
            :loading="isFetching"
            :disabled="isFetching"
          >
            {{ isFetching ? '抓取中...' : '开始抓取' }}
          </a-button>
          <a-button
            style="margin-left: 12px"
            @click="router.back()"
            :disabled="isFetching"
          >
            返回
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<style scoped>
.add-picture-batch-page {
  max-width: 800px;
  margin: 24px auto;
  padding: 0 24px;
}

.progress-section {
  margin-bottom: 20px;
}

.progress-info {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}
</style>
